package sms;

import java.sql.ResultSet;
import java.sql.SQLException;

import dbmanager.DBManager;

public class SendSMS 
{
	DBManager database;
	Modem modem;
	
	public SendSMS() 
	{
		modem = new Modem("/dev/ttyUSB0","230400");
		database = new DBManager();
		database.getConnect();
	}
	
	public SendSMS(PortHandler handle) 
	{
		modem = new Modem(handle);
	}
	
	public void setDatabase(DBManager database)
	{
		this.database = database;
	}
	public void sendSMS()
	{
		while(true)
		{
			System.out.println("THIS IS RECEVIE METHOD");
		//	modem.SendSms("+919922930640","hi",3);
			ResultSet rs = database.getSelect("SELECT * FROM sms where send = 1 and status =0 or (send = 1 and status =0 and schduleAt IS NULL)");
			
			try 
			{
				while(rs.next())
				{
					String mobile = rs.getString("mobile");
					String message = rs.getString("message");
					if(!mobile.equals("+911234567891")||mobile.length()<10)
					{
						mobile=mobile.replace("+91", "0");
						int i=1;
						while(message.length()>160)
						{
							String message1 = message.substring(0,150) + " $part "+i+++"$";
							message = "$part "+i+" $ "+message.substring(150);
							modem.SendSms(mobile, message1, 3);
						}
						if(modem.SendSms(mobile, message, 3))
						{
							System.out.println("Meesage Sent :"+message);
							String id = rs.getString("id");
							database.getUpdate("update sms set status = 5 where id="+id);
						}
					}
					else
					{
						String id = rs.getString("id");
						database.getUpdate("update sms set status = 5 where id="+id);
					}
				}
				rs.close();
				try 
				{
					Thread.sleep(2000);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			catch (SQLException e) {
				e.printStackTrace();
			}
			
		}
	}
	
	public static void main(String[] args) {
		SendSMS sms = new SendSMS();
		DBManager db = new DBManager();
		db.getConnect();
		sms.setDatabase(db);
		sms.sendSMS();
	}
}
